import axios from 'axios'
import {ElMessage} from "element-plus";
import {useUserInfoStore} from "@/stores/user.js";
import router from "@/router/index.js";

const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 50000,
})
// axios请求拦截器
instance.interceptors.request.use(config => {
  const userStore = useUserInfoStore()
  const token = userStore.userInfo.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
instance.interceptors.response.use(
  res => {
    if (res.status === 200) {
      return res.data
    } else {
      ElMessage.error(res.data.message)
    }

  },
    e => {
    const userStore = useUserInfoStore()
    if (e.response && e.response.status === 401) {
      ElMessage.error('身份校验失败')
      router.push('/login')
      userStore.removeUserInfo()
    }
    return Promise.reject(e)
})

export default instance
